package com.blumov.fastbox.application.configuration;

import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Properties;

import org.apache.log4j.Logger;

import com.blumov.fastbox.domain.enums.ErrorCode;
import com.blumov.fastbox.domain.exceptions.NonBusinessException;


/**
 * Una implementacion de {@link Configuration}
 * 
 * @author Bruno Masci
 */
public class ConfigurationImpl implements Configuration {

	private Properties configurationProperties;
	
	Logger logger = Logger.getLogger(ConfigurationImpl.class);


	/**
	 * obtains the property value. <br>
	 * it assumes that the property has always a value.
	 * 
	 * @param key the property key
	 * @return the property value
	 * @throws NonBusinessException when property is not found
	 * @see {@link ErrorCode#E0008}
	 */
	private String getProperty(String key) {
		String property = configurationProperties.getProperty(key);
		if (property == null) {
			throw new NonBusinessException(ErrorCode.E0008, key);
		}
		return property;
	}
	

	/* (non-Javadoc)
	 * @see com.epidataconsulting.vdh.networking.configuration.Configuration#getDateFormatter()
	 */
	public SimpleDateFormat getDateFormatter() {
		return new SimpleDateFormat(Configuration.FORMAT_DD_MM_YYYY);
	}



	/**
	 * @param configurationProperties the configurationProperties to set
	 */
	public void setConfigurationProperties(Properties configurationProperties) {
		this.configurationProperties = configurationProperties;
	}


	/*
	 * (non-Javadoc)
	 * 
	 * @see com.epidataconsulting.vdh.networking.configuration.Configuration#getNetinerAddress()
	 */
	public String getNetinerAddress() {
		return this.getEncodedProperty(Constants.NETINER_URL);
	}

	public String getNetinerPort() {
		return this.getEncodedProperty(Constants.NETINER_PORT);
	}
	
	

	/**
	 * obtiene el valor de la propiedad con el correspondiente encoding.
	 * 
	 * @see Configuration#PROPERTIES_ENCODING
	 * @param key the property key
	 * @return the property value with the proper encoding
	 */
	private String getEncodedProperty(String key) {
		String encodedProperty = "";
		try {
			String property = getProperty(key);
			if (property == null) {
				throw new NonBusinessException(ErrorCode.E0008, key);
			}
			encodedProperty = new String(property.getBytes(), PROPERTIES_ENCODING);
		} catch (UnsupportedEncodingException e) {
			logger.warn(ErrorCode.E0007);
		}
		return encodedProperty;
	}
}
